<template>
	<div class="page">
		<div class="goods-menu" ref="menuWrapper">
			<ul v-for="(item, index) in goodsMenuData" :key="index">
				<p class="item title">{{item.name}}</p>
				<li 
					class="item" 
					v-for="(temp, index) in item.subCategories" 
					:key="index" 
					@click="selectMenu(temp.levelIndex, $event)">
					<span 
						class="li-item">{{temp.name}}</span>
					<p :class="{'item-current':currentIndex === temp.levelIndex}" ></p>
				</li>
			</ul>
		</div>
		<div class="goods-main" ref="goodsWrapper" @scroll="scrollHandler">
			<div class="pro-item" v-for="item in productList">
				<div class="goods-wrapper" v-for="(temp, index) in item" :key="index">
					<p class="title">{{temp.name}}</p>
					<div class="goods-items" v-if="temp.proList != null">
						<div class="goods-item" 
							v-for="(stemp, index) in temp.proList" 
							:key="index" 
							@click="addCart(stemp)">
							<img :src="'http://120.77.58.203:8088/hq-admin/file/v1/getImg?path=' + stemp.imgUrl + '&isCrop=1&w=200&h=200'" alt="">
							<!-- <img :src="'http://10.0.251.180:8080/hq-admin/file/v1/getImg?path=' + stemp.imgUrl + '&isCrop=1&w=200&h=200'" alt=""> -->
							<p class="goods-name" :title="stemp.name">{{stemp.name}}</p>
							<p class="goods-price">￥{{stemp.price}}</p>
							<p class="goods-totalNumber" v-if="stemp.number < 10">剩余数量：{{stemp.number}}</p>
						</div>
					</div>
					<div class="goods-items" v-else>
						<div class="goods-item">
							<p>暂无商品</p>
						</div>
					</div>
				</div>
			</div>
		</div>
		<div class="goods-cart">
			<XGoodsCartModule 
				:data="goodsData"
				@on-click-action="clickAction"
				@on-submit="clickCardSubmit">
			</XGoodsCartModule>
		</div>
		<!-- 下单弹窗 -->
		<div v-if="orderData.isShow">
			<XGoodsOrderModal 
				:data="orderData"
				@on-click-double="clickDouble"
				@on-submit="clickOrderSubmit">
			</XGoodsOrderModal>
		</div>
		<!-- 生成订单弹窗 -->
		<div v-if="orderModalData.isShow">
			<XOrderModal 
				:data="orderModalData"
				@on-qrcode="clickQrcode"
				@on-action="authcode">
			</XOrderModal>
		</div>
	</div>
</template>

<script>
var $this = null;
import $ from 'jquery'
import {formatImgUrl} from '@/common/js/util_imgUrl.js'
import productService from '@/network/service/productService.js'
import XGoodsCartModule from '@/pages/goods/view/XGoodsCartModule'
import XGoodsOrderModal from '@/pages/goods/view/XGoodsOrderModal'
import XOrderModal from '@/pages/goods/view/XOrderModal'
export default {
	components: {
		XGoodsCartModule,XGoodsOrderModal,XOrderModal
	},
	data() {
		return {
			oid: '',
			orderNo: '',
			listHeight: [], //存储商品高度
			scrollY: 0, //滑动距离
			goodsMenuData: [],//商品菜单
			productList: [],
			goodsData: [], //购物车商品数据
			orderData: {//下单数据
				isOpen: true,
				isShow: false,
				isLoading: false,
				data: {},
				form: {},
			},
			D_proData: {
				isShow: false,
				cardData: [],
			},
			orderModalData: {
				isShow: false,
				data: {
					paymentType: null,
					
				}
			}
		}
	},
	mounted () {
		this.getAllCategories();
		this.getAllProducts();
		this.cancelDouble();
		$this = this;
	},
	watch: {
		'orderData.isShow': (val) => {
			if (val == false) {
				$this.cancelDouble();
			}
		}
	},
	computed: {
		currentIndex() {
			for(let i = 0; i<this.listHeight.length; i++) {
				let height1 = this.listHeight[i];//当前menu子块的高度
				let height2 = this.listHeight[i+1];//下一个menu子块的高度
				//滚动到底部的时候,height2为undefined,需要考虑这种情况
				//需要确定是在两个menu子块的高度区间
				if (!height2 || (this.scrollY >= height1 && this.scrollY < height2)) {
					return i;
				}
			}
			return 0;
		}
	},
	methods: {
		cancelDouble() {
			this.D_proData.isShow = false;
			this.D_proData.cardData = [];
			localStorage.setItem('D_proData', JSON.stringify(this.D_proData));
		},
		scrollHandler (e) {
			this.scrollY = e.target.scrollTop;
		},
		selectMenu(index, event) {
			let goodsList = this.$refs.goodsWrapper.children;
			$('.goods-main').animate({scrollTop: this.listHeight[index]}, 300)
			
		},
		//计算goods内部块的高度
		_calcHeight() {
			let mainHeight = $('.goods-main').height();
			// let mainLastHeight = $('.goods-main').children('div:last-child').height();
			$('.goods-main').children('div:last-child').css('height', mainHeight)
			let goodsList = $('.pro-item');
			let height = 0;
			this.listHeight.push(height);
			for (let i = 0; i < goodsList.length; i++) {
				let item = goodsList[i];
				height += item.clientHeight;
				this.listHeight.push(height);
			}
			this.listHeight[this.listHeight.length - 2] -= 16
		},
		addCart(item) {
			console.log(item);
			let params = {
				name: item.name,
				pid: item.pid,
				unit: item.unit,
				price: item.price,
				number: item.count,
				totalNumber: item.number,
			}
			if (item.number != 0) {
				if (this.goodsData.length == 0) {
					this.goodsData.push(params)
				} else {
					var isExists = 1;
					for (var i = 0; i < this.goodsData.length; i++) {
						let temp = this.goodsData[i];
						if(temp.pid == item.pid){
							if (temp.number < temp.totalNumber) {
								temp.number += 1;
							} else {
								temp.number = temp.totalNumber;
							}
							isExists = 1;
							break;
						}
						if(temp.pid != params.pid){
							isExists = 0;
							continue;
						}
						
					}
					if(isExists==0){
						this.goodsData.push(params);
					}
				}
			} else {
				this.$Message.error('库存不足，请补充库存')
			}
		},
		clickAction(type, formdata, index) {
			switch(type) {
				case 'clear':
					this.goodsData = [];
				break;
				case 'reduce': 
					if (formdata.number !=1) {
						formdata.number -= 1;
					} else {
						this.goodsData.splice(index, 1);
					}
				break;
				case 'add': 
					if (formdata.number == formdata.totalNumber) {
						formdata.number = formdata.totalNumber;
					} else {
						formdata.number += 1;
					}
				break;
			}
		},
		clickDouble(type) {
			if (type == 'open') {
				this.orderData.isOpen = true;
				this.D_proData.isShow = true;
				localStorage.setItem('D_proData', JSON.stringify(this.D_proData));				
			} else if (type == 'close') {
				this.orderData.isOpen = false;
				this.D_proData.isShow = false;
				localStorage.setItem('D_proData', JSON.stringify(this.D_proData));
			}
		},
		clickCardSubmit(formdata) {
			this.orderData.isShow = true;
			this.orderData.data = formdata;
			this.orderData.form = {};
			this.orderData.true = false;
			this.D_proData.cardData = formdata;
			this.D_proData.isShow = true;
			localStorage.setItem('D_proData', JSON.stringify(this.D_proData));
		},
		clickOrderSubmit(type, params, formdata) {
			if (type == 'submit') {
				this.putProOrder(params, formdata);
				this.D_proData.cardData = formdata;
				this.D_proData.isShow = true;
				localStorage.setItem('D_proData', JSON.stringify(this.D_proData));
			} else if (type == 'cancel') {
				formdata.isShow = false;
				this.cancelDouble();
			}
		},
		clickQrcode() {

		},

		getAllCategories() {
			productService.getAllCategories().then(res => {
				let result = res.data;
				let code = result.rescode;
				if (code == 100) {
					this.goodsMenuData = result.data.category;
				} else {
					this.$Message.error(result.msg);
				}
			}, error => {
				this.$Message.error('服务器异常，请稍后再试')
			})
		},
		getAllProducts() {
			let params = {
				page: 0,
				pageSize: 1000
			}
			productService.getAllProducts(params).then(res => {
				let result = res.data;
				let code = result.rescode;
				if (code == 100) {
					this.goods = result.data;
					let temp = null;
					let tarr = [];
					let data = result.data;
					temp = data[0];
					tarr.push(temp);
					for(let i = 0; i < data.length; i++) {
						if (data[i].proList != null) {
							data[i].proList.map(item => {
								this.$set(item, 'count', 1);
							})
						}
					}
					for (var i = 1; i < data.length; i++) {
						if (temp.parentId != data[i].parentId) {
							this.productList.push(tarr);
							tarr = [];
						}
						temp = data[i];
						tarr.push(temp);
					}
					this.productList.push(tarr);
					setTimeout(() => {
						this._calcHeight()
					}, 1)
				} else {
					this.$Message.error(result.msg);
				}
			}, error => {
				this.$Message.error('服务器异常，请稍后再试')
			})
		},
		putProOrder(params, formdata) {
			let param ={
				pros: params.pros,
	            actualMoeny: params.actualMoeny,
	            payType: params.payType,
	            isHand: params.isHand,
	            roomId: params.roomId,
	            isAuth: 0,
	            authMoney: '',
	            authAccId: '',
				vipCardId: '',
				isDeliver: params.isDeliver,
	            deviceMac: '',
			}
			// console.log(formdata);
			console.log(params);
			formdata.isLoading = true;
			productService.putProOrder(param).then(res => {
				let result = res.data;
				let code = result.rescode;
				if (code == 100) {
					formdata.isLoading = false;
					this.$Message.success('下单成功')
					this.oid = result.data.oid;
					this.orderNo = result.data.orderNo;
					formdata.isShow = false;
					this.goodsData = [];
					this.getAllProducts();
					// this.orderModalData.isShow = true;
				} else {
					formdata.isLoading = false;
					this.$Message.error(result.msg);
				}
			}, error => {
				this.$Message.error('服务器异常，请稍后再试')
			})
		},
		getAliPay() {
			productService.aliScanQrcode2Store(this.orderNo).then(res => {
				let result = res.data;
			}, error => {
				this.$Message.error('服务器异常，请稍后再试')
			})
		},
		authcode(formData) {
			let params = {
				outTradeNo: this.orderNo,
				authCode: formData,
			}
			productService.aliScanAuthCode2Store(params).then(res => {
				let result = res.data;
				console.log(result);
			}, error => {
				this.$Message.error('服务器异常，请稍后再试')
			})
		}
	}
}
</script>

<style scoped lang="less">
.page {
	width: 100%;
	height: 100%;
	display: flex;
	.goods-menu {
		margin-right: .3rem;
		width: 1.4rem;
		overflow: auto;
		background: rgba(255,255,255,0.1);
		color: #fff;
		opacity: 0.84;
		font-size: .14rem;
		.item {
			width: 100%;
			height: .5rem;
			line-height: .5rem;
			text-align: center;
			.item-current {
				width: .3rem;
				margin: 0 auto;
				border-bottom: 1px solid;
				position: relative;
			}
		}
		li {
			cursor: pointer;
		}
		a {
			color: #fff;
			opacity: 0.84;
			font-size: .14rem;
		}
		.title {
			background: rgba(255,255,255,0.3);
		}
	}
	.goods-main {
		width: 7.2rem;
		margin-right: .3rem;
		overflow: auto;
		.goods-wrapper {
			.title {
				border-bottom: .01rem solid rgba(255,255,255,0.4);
				padding: .1rem 0;
				color: #fff;
			}
			.goods-items {
				.goods-item {
					width: 1.6rem;
					min-height: 2rem;
					display: inline-block;
					margin-right: .2rem;
					margin-top: .25rem;
					cursor: pointer;
					position: relative;
					img {
						width: 100%;
						height: 1.6rem;
					}
					p {
						text-align: center;
						color: #fff;
					}
					.goods-name {
						white-space:nowrap;
						overflow:hidden;
						text-overflow:ellipsis;
					}
					.goods-price {
						color: #CD2A86;
					}
					.goods-totalNumber {
						width: 100%;
						padding: .05rem 0;
						position: absolute;
						top: 0;
						background: #f13232;
					}
				}
			}
		}
	}
	.goods-cart {
		width: 4.5rem;
		height: 100%;
		overflow: auto;
		float: left;
		background: rgba(255,255,255,0.1);
		border-radius: .08rem .08rem .08rem .08rem;
	}
	.current {
		// border-bottom: .01rem solid;
	}
	
}
</style>